#include "socket.hpp"

Socket::Socket()
{
  ref_socket=socket(AF_INET,SOCK_DGRAM,0);
  bzero(&socket_server_info,sizeof(socket_server_info));
  bzero(&socket_com_info,sizeof(socket_com_info));
}

Socket::Socket(const char* ip_server,unsigned int port_server,unsigned int port_communication)
{
  ref_socket=socket(AF_INET,SOCK_DGRAM,0);

  bzero(&socket_server_info,sizeof(socket_server_info));
  socket_server_info.sin_family=AF_INET;
  socket_server_info.sin_addr.s_addr=inet_addr(ip_server);
  socket_server_info.sin_port=htons(port_server);

  bzero(&socket_com_info,sizeof(socket_com_info));
  socket_com_info.sin_family=AF_INET;
  socket_com_info.sin_addr.s_addr=inet_addr(ip_server);
  socket_com_info.sin_port=htons(port_communication);

  bind(ref_socket,(struct sockaddr*)&socket_com_info,sizeof(socket_com_info));
}

void Socket::send_data(string data)
{
  //TODO : Gestion derreur
  sendto(ref_socket,data.c_str(),data.length(),0,(struct sockaddr*)&socket_server_info,sizeof(socket_server_info));
}

string Socket::recieve_data()
{
  struct sockaddr_in socket_recieve_info;
  socklen_t length_struct=sizeof(socket_recieve_info);
  char r_message[MAX_SIZE_RECIEVE];

  recvfrom(ref_socket,r_message,MAX_SIZE_RECIEVE,0,(struct sockaddr*)&socket_recieve_info,&length_struct);

  return (string)r_message;
}

void Socket::close_socket()
{
  close(ref_socket);
}
